#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>

// gcc -o mysql_example mysql_example.c -lmysqlclient

int main() {
    MYSQL *conn;  // MySQL连接句柄
    MYSQL_RES *result;  // 查询结果集
    MYSQL_ROW row;  // 查询结果行
    char *server = "localhost";  // 数据库服务器地址
    char *user = "root";  // 数据库用户名
    char *password = "123456";  // 数据库密码
    char *database = "testdb";  // 数据库名称

    // 初始化MySQL连接
    conn = mysql_init(NULL);

    // 连接到数据库
    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }

    printf("Connected to MySQL database successfully!\n");

    // 创建表
    const char *create_table_query = 
        "CREATE TABLE IF NOT EXISTS users ("
        "id INT AUTO_INCREMENT PRIMARY KEY, "
        "name VARCHAR(50), "
        "age INT)";
    if (mysql_query(conn, create_table_query)) {
        fprintf(stderr, "Failed to create table: %s\n", mysql_error(conn));
        exit(1);
    }
    printf("Table created successfully!\n");

    // 插入数据
    const char *insert_query = 
        "INSERT INTO users (name, age) VALUES ('John Doe', 30), ('Jane Doe', 25)";
    if (mysql_query(conn, insert_query)) {
        fprintf(stderr, "Failed to insert data: %s\n", mysql_error(conn));
        exit(1);
    }
    printf("Data inserted successfully!\n");

    // 查询数据
    const char *select_query = "SELECT id, name, age FROM users";
    if (mysql_query(conn, select_query)) {
        fprintf(stderr, "Failed to query data: %s\n", mysql_error(conn));
        exit(1);
    }

    result = mysql_use_result(conn);

    // 输出查询结果
    printf("ID\tName\tAge\n");
    while ((row = mysql_fetch_row(result)) != NULL) {
        printf("%s\t%s\t%s\n", row[0], row[1], row[2]);
    }

    // del数据
    const char *select_query = "SELECT id, name, age FROM users";
    if (mysql_query(conn, select_query)) {
        fprintf(stderr, "Failed to query data: %s\n", mysql_error(conn));
        exit(1);
    }

    // 清理资源
    mysql_free_result(result);
    mysql_close(conn);

    return 0;
}
